#ifndef CAESARCIPHER_H
#define CAESARCIPHER_H

#include <iostream>
#include <algorithm>
using namespace std;

class CaesarCipher {
private:
    int key;    //密钥
    CaesarCipher():key(10) {}
    static CaesarCipher* instance;

public:
    static CaesarCipher* getInstance()
    {
        if(instance==nullptr)
        {
            instance=new CaesarCipher();
        }
        return instance;
    }

    int getKey()    {return key;}

    bool isChar(string s) {
        bool isPhontic = false;
        for (int i = 0; i < s.size(); i++) {
            char str = s[i];
            isPhontic = (str >= 'a' && str <= 'z') || (str >= 'A' && str <= 'Z');
            if (!isPhontic) {
                return false;
            }
        }
        return true;
    }

    bool isNum(string str) {
        for (int i = 0; i < str.size(); i++) {
            int tmp = (int)str[i];
            if (tmp >= 48 && tmp <= 57)
                continue;
            else
                return false;
        }
        return true;
    }

public:
    //去除str字符串内的全部空格
    string trimAll(string str) {
        string::iterator pos = str.begin();
        while (1) {
            pos = find(pos, str.end(), ' ');
            if (pos == str.end()) break;
            str.erase(pos);
        }
        return str;
    }

    //加密，返回一个加密的字符串s
    string Encrypt(string plaintext, int key) {
        string s="";
        for (int i = 0; i < plaintext.size(); i++) {
            if ('a' <= plaintext[i] && plaintext[i] <= 'z')
                s += char((plaintext[i] + key - 'a') % 26 + 'a');
            else if ('A' <= plaintext[i] && plaintext[i] <= 'Z')
                s += char((plaintext[i] + key - 'A') % 26 + 'A');
            else if ('0' <= plaintext[i] && plaintext[i] <= '9')
                s += char((plaintext[i] -key+i));
        }
        return s;
    }

    //解密，返回一个解密后的字符串plaintext
    string Decrypt(string ciphertext, int key) {
        int k = 0 - key;
        string plaintext = "";
        for (int i = 0; i < ciphertext.size(); i++) {
            char c = ciphertext[i];
            if (c >= 'a' && c <= 'z') {
                c += k % 26;
                if (c < 'a')
                    c += 26;
                if (c > 'z')
                    c -= 26;
            }
            else if (c >= 'A' && c <= 'Z') {
                c += k % 26;
                if (c < 'A')
                    c += 26;
                if (c > 'Z')
                    c -= 26;
            }
            else if (c >=-60  && c<100 ) {
                c += (key-i);
                if (c < '0')
                    c += 10;
                if (c > '9')
                    c -= 10;
            }
            plaintext += c;
        }
        return plaintext;
    }
};

#endif // CAESARCIPHER_H
